package com.cs.peanut.base_app.service;

import android.text.TextUtils;

import com.cs.peanut.base.util.GsonUtil;
import com.cs.peanut.base_app.Servlet;

import java.util.ArrayList;
import java.util.List;

import fi.iki.elonen.NanoHTTPD;

/**
 * Created by peanut on 2018/06/13.
 */

public class AndroidWebServer extends NanoHTTPD {
    public static final String MIME_JSON = "application/json";
    public static final String MIME_OCTET_STREAM = "application/octet-stream";
    private List<Servlet> servlets = new ArrayList<>();

    public AndroidWebServer(int port) {
        super(port);
    }

    public AndroidWebServer(String hostname, int port) {
        super(hostname, port);
    }

    public void addServlet(Servlet servlet) {
        servlets.add(servlet);
    }

    @Override
    public Response serve(IHTTPSession session) {
        String url = session.getUri();
        String[] paths = url.split("/", 3);
        String path;
        if (paths.length <= 1) {
            path = "index";
        } else {
            path = paths[1];
        }
        if (TextUtils.isEmpty(path))
            path = "index";
        Response response = null;
        for (Servlet servlet : servlets) {
            try {

                java.lang.reflect.Method methodRef = servlet.getClass().getMethod(path,
                        IHTTPSession.class);
                response = (Response) methodRef.invoke(servlet, session);
            } catch (Exception ignored) {
            }
            if (response != null)
                return response;
        }
        return printError(new AppError(404,"Not Found"));
    }

    public static Response printSuccess(Object obj) {
        return AndroidWebServer.newFixedLengthResponse(Response.Status.OK, AndroidWebServer
                .MIME_JSON, GsonUtil.defaultGson().toJson(obj));
    }

    public static Response printError(AppError error) {
        return AndroidWebServer.newFixedLengthResponse(Response.Status.NOT_FOUND,
                AndroidWebServer.MIME_JSON, GsonUtil.defaultGson().toJson(error));
    }

    public static Response printError(String error) {
        return printError(new AppError(error));
    }
}
